g1t/apps/docs/src/pages/[...slug].md.ts
| 1 | import type { APIRoute, GetStaticPaths } from 'astro'; |
| 2 | import { getCollection } from 'astro:content'; |
| 3 | |
| 4 | import { AGENTS, AGENTS_WITH_TOKEN, type AgentSetup } from '../data/agents'; |
| 5 | |
| 6 | /** The agent toggle, as plain Markdown: each agent's snippet under its name. */ |
| 7 | function agentsMarkdown(agents: AgentSetup[]): string { |
| 8 | return agents |
| 9 | .map((agent) => { |
| 10 | const where = agent.file ? ` (in \`${agent.file}\`)` : ''; |
| 11 | const then = agent.then ? `\n\n${agent.then}` : ''; |
| 12 | const fence = '```'; |
| 13 | return `**${agent.label}**${where}:\n\n${fence}${agent.lang}\n${agent.code}\n${fence}${then}`; |
| 14 | }) |
| 15 | .join('\n\n'); |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Every page as Markdown, at its path plus `.md`, for "Copy page" and for |
| 20 | * agents that read the docs: the title, what it is about, then the page. |
| 21 | */ |
| 22 | export const getStaticPaths: GetStaticPaths = async () => { |
| 23 | const pages = await getCollection('docs'); |
| 24 | return pages.map((page) => ({ |
| 25 | params: { slug: page.id === '' ? 'index' : page.id }, |
| 26 | props: { page }, |
| 27 | })); |
| 28 | }; |
| 29 | |
| 30 | export const GET: APIRoute = ({ props }) => { |
| 31 | const { page } = props as { page: Awaited<ReturnType<typeof getCollection<'docs'>>>[number] }; |
| 32 | const { title, description } = page.data; |
| 33 | // MDX pages keep their markup; strip imports and leave the rest readable. |
| 34 | const body = (page.body ?? '') |
| 35 | .replace(/^import .*$/gm, '') |
| 36 | .replace(/^([ \t]*)<AgentSetup( variant="token")? \/>$/gm, (_match, indent: string, token?: string) => |
| 37 | agentsMarkdown(token ? AGENTS_WITH_TOKEN : AGENTS) |
| 38 | .split('\n') |
| 39 | .map((line) => (line ? indent + line : line)) |
| 40 | .join('\n'), |
| 41 | ) |
| 42 | .trim(); |
| 43 | const text = `# ${title}\n\n${description ? `> ${description}\n\n` : ''}${body}\n`; |
| 44 | return new Response(text, { headers: { 'content-type': 'text/markdown; charset=utf-8' } }); |
| 45 | }; |